<!DOCTYPE html>
<html lang="en">
<head>
  <title>Vert.x MongoDB Client - Vert.x</title>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta content="width=device-width, initial-scale=1.0" name="viewport">
  <meta content="Vert.x is a tool-kit for building reactive applications on the JVM." name="description">
  <link href="http://vertx.io/stylesheets/docs.css" media="screen" rel="stylesheet">
  <link href="http://vertx.io/stylesheets/font-awesome.min.css" media="screen" rel="stylesheet">
  <link href="http://vertx.io/javascripts/styles/rainbow.min.css" media="screen" rel="stylesheet">
  <!-- IE 6-8 support of HTML 5 elements -->
  <!--[if lt IE 9]>
  <script src="http://static.jboss.org/theme/js/libs/html5/pre3.6/html5.min.js"></script>
  <![endif]-->

  <link rel="apple-touch-icon" sizes="57x57" href="http://vertx.io/assets/favicons/vertx-favicon-7/apple-touch-icon-57x57.png">
  <link rel="apple-touch-icon" sizes="60x60" href="http://vertx.io/assets/favicons/vertx-favicon-7/apple-touch-icon-60x60.png">
  <link rel="apple-touch-icon" sizes="72x72" href="http://vertx.io/assets/favicons/vertx-favicon-7/apple-touch-icon-72x72.png">
  <link rel="apple-touch-icon" sizes="76x76" href="http://vertx.io/assets/favicons/vertx-favicon-7/apple-touch-icon-76x76.png">
  <link rel="apple-touch-icon" sizes="114x114" href="http://vertx.io/assets/favicons/vertx-favicon-7/apple-touch-icon-114x114.png">
  <link rel="apple-touch-icon" sizes="120x120" href="http://vertx.io/assets/favicons/vertx-favicon-7/apple-touch-icon-120x120.png">
  <link rel="apple-touch-icon" sizes="144x144" href="http://vertx.io/assets/favicons/vertx-favicon-7/apple-touch-icon-144x144.png">
  <link rel="apple-touch-icon" sizes="152x152" href="http://vertx.io/assets/favicons/vertx-favicon-7/apple-touch-icon-152x152.png">
  <link rel="apple-touch-icon" sizes="180x180" href="http://vertx.io/assets/favicons/vertx-favicon-7/apple-touch-icon-180x180.png">
  <link rel="icon" type="image/png" href="http://vertx.io/assets/favicons/vertx-favicon-7/favicon-32x32.png" sizes="32x32">
  <link rel="icon" type="image/png" href="http://vertx.io/assets/favicons/vertx-favicon-7/android-chrome-192x192.png" sizes="192x192">
  <link rel="icon" type="image/png" href="http://vertx.io/assets/favicons/vertx-favicon-7/favicon-96x96.png" sizes="96x96">
  <link rel="icon" type="image/png" href="http://vertx.io/assets/favicons/vertx-favicon-7/favicon-16x16.png" sizes="16x16">
  <link rel="manifest" href="http://vertx.io/assets/favicons/vertx-favicon-7/manifest.json">
  <link rel="mask-icon" href="http://vertx.io/assets/favicons/vertx-favicon-7/safari-pinned-tab.svg" color="#5bbad5">
  <meta name="msapplication-TileColor" content="#7d3194">
  <meta name="msapplication-TileImage" content="http://vertx.io/assets/favicons/vertx-favicon-7/mstile-144x144.png">
  <meta name="theme-color" content="#ffffff">

  <link href="http://fonts.googleapis.com/css?family=Ubuntu:400,500,700,400italic" rel="stylesheet" type="text/css">
  <link rel="alternate" type="application/rss+xml" title="RSS"
     href="http://vertx.io/feed.xml">
  <script>
    (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
      (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
      m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
    })(window,document,'script','//www.google-analytics.com/analytics.js','ga');
    ga('create', 'UA-30144458-1', 'auto');
    ga('create', 'UA-71153120-1', 'auto', 'tracker');
    ga('send', 'pageview');
    ga('tracker.send', 'pageview');
  </script>
</head>
<body>

<a href="http://www.reactivemanifesto.org/" id="reactive-manifesto-banner">
  <img style="border: 0; position: fixed; right: 0; top:0; z-index: 9000"
    src="http://d379ifj7s9wntv.cloudfront.net/reactivemanifesto/images/ribbons/we-are-reactive-black-right.png">
</a>

<a id="skippy" class="sr-only sr-only-focusable" href="#content"><div class="container"><span class="skiplink-text">Skip to main content</span></div></a>

<header class="navbar navbar-default navbar-static-top" id="top" role="banner">
  <div class="container">
    <div class="navbar-header">
      <button class="navbar-toggle collapsed" type="button" data-toggle="collapse" data-target="#vertx-navbar-collapse">
        <span class="sr-only">Toggle navigation</span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
      </button>
      <a href="http://vertx.io/" class="navbar-brand"><img alt="Brand" src="http://vertx.io/assets/logo-sm.png"></a>
    </div>
    <nav class="collapse navbar-collapse" id="vertx-navbar-collapse">
      <ul class="nav navbar-nav navbar-right">
        <li><a href="http://vertx.io/download/">Download</a></li>
        <li><a href="http://vertx.io/docs/">Documentation</a></li>
        <li><a href="https://github.com/vert-x3/wiki/wiki">Wiki</a></li>
        <li><a href="http://vertx.io/community/">Community</a></li>
        <li><a href="http://vertx.io/materials/">Materials</a></li>
        <li><a href="http://vertx.io/blog/">Blog</a></li>        
      </ul>
    </nav>
  </div>
</header>



  <div class="page-header" id="content">
    <div class="container">
      <div class="row">
        <div class="col-sm-12">
          <h1>Vert.x MongoDB Client</h1>
          
        </div>
      </div>
    </div>
  </div>




<div id="content">
  <div class="container docs-content">
    <div class="row">
      <div class="col-sm-12 col-md-push-9 col-md-3 hidden-xs hidden-sm">
        <div id="sidebar" data-spy="affix">
          <ul class="sectlevel1">
<li><a href="#_using_vert_x_mongodb_client">Using Vert.x MongoDB Client</a></li>
<li><a href="#_creating_a_client">Creating a client</a>
<ul class="sectlevel2">
<li><a href="#_using_the_default_shared_pool">Using the default shared pool</a></li>
<li><a href="#_specifying_a_pool_source_name">Specifying a pool source name</a></li>
<li><a href="#_creating_a_client_with_a_non_shared_data_pool">Creating a client with a non shared data pool</a></li>
</ul>
</li>
<li><a href="#_using_the_api">Using the API</a>
<ul class="sectlevel2">
<li><a href="#_saving_documents">Saving documents</a></li>
<li><a href="#_inserting_documents">Inserting documents</a></li>
<li><a href="#_updating_documents">Updating documents</a></li>
<li><a href="#_replacing_documents">Replacing documents</a></li>
<li><a href="#_finding_documents">Finding documents</a></li>
<li><a href="#_finding_a_single_document">Finding a single document</a></li>
<li><a href="#_removing_documents">Removing documents</a></li>
<li><a href="#_removing_a_single_document">Removing a single document</a></li>
<li><a href="#_counting_documents">Counting documents</a></li>
<li><a href="#_managing_mongodb_collections">Managing MongoDB collections</a></li>
<li><a href="#_running_other_mongodb_commands">Running other MongoDB commands</a></li>
<li><a href="#_mongodb_extended_json_support">MongoDB Extended JSON support</a></li>
</ul>
</li>
<li><a href="#_configuring_the_client">Configuring the client</a></li>
</ul>
        </div>
      </div>
      <div class="col-sm-12 col-md-pull-3 col-md-9">
        <div class="toc hidden-md hidden-lg">
          <h2>Table of Contents</h2>
          <ul class="sectlevel1">
<li><a href="#_using_vert_x_mongodb_client">Using Vert.x MongoDB Client</a></li>
<li><a href="#_creating_a_client">Creating a client</a>
<ul class="sectlevel2">
<li><a href="#_using_the_default_shared_pool">Using the default shared pool</a></li>
<li><a href="#_specifying_a_pool_source_name">Specifying a pool source name</a></li>
<li><a href="#_creating_a_client_with_a_non_shared_data_pool">Creating a client with a non shared data pool</a></li>
</ul>
</li>
<li><a href="#_using_the_api">Using the API</a>
<ul class="sectlevel2">
<li><a href="#_saving_documents">Saving documents</a></li>
<li><a href="#_inserting_documents">Inserting documents</a></li>
<li><a href="#_updating_documents">Updating documents</a></li>
<li><a href="#_replacing_documents">Replacing documents</a></li>
<li><a href="#_finding_documents">Finding documents</a></li>
<li><a href="#_finding_a_single_document">Finding a single document</a></li>
<li><a href="#_removing_documents">Removing documents</a></li>
<li><a href="#_removing_a_single_document">Removing a single document</a></li>
<li><a href="#_counting_documents">Counting documents</a></li>
<li><a href="#_managing_mongodb_collections">Managing MongoDB collections</a></li>
<li><a href="#_running_other_mongodb_commands">Running other MongoDB commands</a></li>
<li><a href="#_mongodb_extended_json_support">MongoDB Extended JSON support</a></li>
</ul>
</li>
<li><a href="#_configuring_the_client">Configuring the client</a></li>
</ul>
        </div>
        <div id="preamble">
<div class="sectionbody">
<div class="paragraph">
<p>A Vert.x client allowing applications to interact with a MongoDB instance, whether that&#8217;s
saving, retrieving, searching, or deleting documents.</p>
</div>
<div class="paragraph">
<p>Mongo is a great match for persisting data in a Vert.x application
as it natively handles JSON (BSON) documents.</p>
</div>
<div class="paragraph">
<p><strong>Features</strong></p>
</div>
<div class="ulist">
<ul>
<li>
<p>Completely non-blocking</p>
</li>
<li>
<p>Custom codec to support fast serialization to/from Vert.x JSON</p>
</li>
<li>
<p>Supports a majority of the configuration options from the MongoDB Java Driver</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>This client is based on the
<a href="http://mongodb.github.io/mongo-java-driver/3.2/driver-async/getting-started">MongoDB Async Driver</a>.</p>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_using_vert_x_mongodb_client">Using Vert.x MongoDB Client</h2>
<div class="sectionbody">
<div class="paragraph">
<p>To use this project, add the following dependency to the <em>dependencies</em> section of your build descriptor:</p>
</div>
<div class="ulist">
<ul>
<li>
<p>Maven (in your <code>pom.xml</code>):</p>
</li>
</ul>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-xml" data-lang="xml">&lt;dependency&gt;
  &lt;groupId&gt;io.vertx&lt;/groupId&gt;
  &lt;artifactId&gt;vertx-mongo-client&lt;/artifactId&gt;
  &lt;version&gt;3.3.3&lt;/version&gt;
&lt;/dependency&gt;</code></pre>
</div>
</div>
<div class="ulist">
<ul>
<li>
<p>Gradle (in your <code>build.gradle</code> file):</p>
</li>
</ul>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-groovy" data-lang="groovy">compile 'io.vertx:vertx-mongo-client:3.3.3'</code></pre>
</div>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_creating_a_client">Creating a client</h2>
<div class="sectionbody">
<div class="paragraph">
<p>You can create a client in several ways:</p>
</div>
<div class="sect2">
<h3 id="_using_the_default_shared_pool">Using the default shared pool</h3>
<div class="paragraph">
<p>In most cases you will want to share a pool between different client instances.</p>
</div>
<div class="paragraph">
<p>E.g. you scale your application by deploying multiple instances of your verticle and you want each verticle instance
to share the same pool so you don&#8217;t end up with multiple pools</p>
</div>
<div class="paragraph">
<p>The simplest way to do this is as follows:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">var MongoClient = require("vertx-mongo-js/mongo_client");

var client = MongoClient.createShared(vertx, config);</code></pre>
</div>
</div>
<div class="paragraph">
<p>The first call to <code><a href="../../jsdoc/module-vertx-mongo-js_mongo_client-MongoClient.html#createShared">MongoClient.createShared</a></code>
will actually create the pool, and the specified config will be used.</p>
</div>
<div class="paragraph">
<p>Subsequent calls will return a new client instance that uses the same pool, so the configuration won&#8217;t be used.</p>
</div>
</div>
<div class="sect2">
<h3 id="_specifying_a_pool_source_name">Specifying a pool source name</h3>
<div class="paragraph">
<p>You can create a client specifying a pool source name as follows</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">var MongoClient = require("vertx-mongo-js/mongo_client");

var client = MongoClient.createShared(vertx, config, "MyPoolName");</code></pre>
</div>
</div>
<div class="paragraph">
<p>If different clients are created using the same Vert.x instance and specifying the same pool name, they will
share the same pool.</p>
</div>
<div class="paragraph">
<p>The first call to <code><a href="../../jsdoc/module-vertx-mongo-js_mongo_client-MongoClient.html#createShared">MongoClient.createShared</a></code>
will actually create the pool, and the specified config will be used.</p>
</div>
<div class="paragraph">
<p>Subsequent calls will return a new client instance that uses the same pool, so the configuration won&#8217;t be used.</p>
</div>
<div class="paragraph">
<p>Use this way of creating if you wish different groups of clients to have different pools, e.g. they&#8217;re
interacting with different databases.</p>
</div>
</div>
<div class="sect2">
<h3 id="_creating_a_client_with_a_non_shared_data_pool">Creating a client with a non shared data pool</h3>
<div class="paragraph">
<p>In most cases you will want to share a pool between different client instances.
However, it&#8217;s possible you want to create a client instance that doesn&#8217;t share its pool with any other client.</p>
</div>
<div class="paragraph">
<p>In that case you can use <code><a href="../../jsdoc/module-vertx-mongo-js_mongo_client-MongoClient.html#createNonShared">MongoClient.createNonShared</a></code>.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">var MongoClient = require("vertx-mongo-js/mongo_client");

var client = MongoClient.createNonShared(vertx, config);</code></pre>
</div>
</div>
<div class="paragraph">
<p>This is equivalent to calling <code><a href="../../jsdoc/module-vertx-mongo-js_mongo_client-MongoClient.html#createShared">MongoClient.createShared</a></code>
with a unique pool name each time.</p>
</div>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_using_the_api">Using the API</h2>
<div class="sectionbody">
<div class="paragraph">
<p>The client API is represented by <code><a href="../../jsdoc/module-vertx-mongo-js_mongo_client-MongoClient.html">MongoClient</a></code>.</p>
</div>
<div class="sect2">
<h3 id="_saving_documents">Saving documents</h3>
<div class="paragraph">
<p>To save a document you use <code><a href="../../jsdoc/module-vertx-mongo-js_mongo_client-MongoClient.html#save">save</a></code>.</p>
</div>
<div class="paragraph">
<p>If the document has no <code>_id</code> field, it is inserted, otherwise, it is _upserted_. Upserted means it is inserted
if it doesn&#8217;t already exist, otherwise it is updated.</p>
</div>
<div class="paragraph">
<p>If the document is inserted and has no id, then the id field generated will be returned to the result handler.</p>
</div>
<div class="paragraph">
<p>Here&#8217;s an example of saving a document and getting the id back</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-js" data-lang="js">// Document has no id

var document = {
  "title" : "The Hobbit"
};

mongoClient.save("books", document, function (res, res_err) {

  if (res_err == null) {

    var id = res;
    console.log("Saved book with id " + id);

  } else {
    res_err.printStackTrace();
  }

});</code></pre>
</div>
</div>
<div class="paragraph">
<p>And here&#8217;s an example of saving a document which already has an id.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-js" data-lang="js">// Document has an id already

var document = {
  "title" : "The Hobbit",
  "_id" : "123244"
};

mongoClient.save("books", document, function (res, res_err) {

  if (res_err == null) {

    // ...

  } else {
    res_err.printStackTrace();
  }

});</code></pre>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_inserting_documents">Inserting documents</h3>
<div class="paragraph">
<p>To insert a document you use <code><a href="../../jsdoc/module-vertx-mongo-js_mongo_client-MongoClient.html#insert">insert</a></code>.</p>
</div>
<div class="paragraph">
<p>If the document is inserted and has no id, then the id field generated will be returned to the result handler.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-js" data-lang="js">// Document has an id already

var document = {
  "title" : "The Hobbit"
};

mongoClient.insert("books", document, function (res, res_err) {

  if (res_err == null) {

    var id = res;
    console.log("Inserted book with id " + id);

  } else {
    res_err.printStackTrace();
  }

});</code></pre>
</div>
</div>
<div class="paragraph">
<p>If a document is inserted with an id, and a document with that id already eists, the insert will fail:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-js" data-lang="js">// Document has an id already

var document = {
  "title" : "The Hobbit",
  "_id" : "123244"
};

mongoClient.insert("books", document, function (res, res_err) {

  if (res_err == null) {

    //...

  } else {

    // Will fail if the book with that id already exists.
  }

});</code></pre>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_updating_documents">Updating documents</h3>
<div class="paragraph">
<p>To update a documents you use <code><a href="../../jsdoc/module-vertx-mongo-js_mongo_client-MongoClient.html#update">update</a></code>.</p>
</div>
<div class="paragraph">
<p>This updates one or multiple documents in a collection. The json object that is passed in the <code>update</code>
parameter must contain <a href="http://docs.mongodb.org/manual/reference/operator/update-field/">Update Operators</a> and determines
how the object is updated.</p>
</div>
<div class="paragraph">
<p>The json object specified in the query parameter determines which documents in the collection will be updated.</p>
</div>
<div class="paragraph">
<p>Here&#8217;s an example of updating a document in the books collection:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-js" data-lang="js">// Match any documents with title=The Hobbit
var query = {
  "title" : "The Hobbit"
};

// Set the author field
var update = {
  "$set" : {
    "author" : "J. R. R. Tolkien"
  }
};

mongoClient.update("books", query, update, function (res, res_err) {

  if (res_err == null) {

    console.log("Book updated !");

  } else {

    res_err.printStackTrace();
  }

});</code></pre>
</div>
</div>
<div class="paragraph">
<p>To specify if the update should upsert or update multiple documents, use <code><a href="../../jsdoc/module-vertx-mongo-js_mongo_client-MongoClient.html#updateWithOptions">updateWithOptions</a></code>
and pass in an instance of <code><a href="../dataobjects.html#UpdateOptions">UpdateOptions</a></code>.</p>
</div>
<div class="paragraph">
<p>This has the following fields:</p>
</div>
<div class="dlist">
<dl>
<dt class="hdlist1"><code>multi</code></dt>
<dd>
<p>set to true to update multiple documents</p>
</dd>
<dt class="hdlist1"><code>upsert</code></dt>
<dd>
<p>set to true to insert the document if the query doesn&#8217;t match</p>
</dd>
<dt class="hdlist1"><code>writeConcern</code></dt>
<dd>
<p>the write concern for this operation</p>
</dd>
</dl>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-js" data-lang="js">// Match any documents with title=The Hobbit
var query = {
  "title" : "The Hobbit"
};

// Set the author field
var update = {
  "$set" : {
    "author" : "J. R. R. Tolkien"
  }
};

var options = {
  "multi" : true
};

mongoClient.updateWithOptions("books", query, update, options, function (res, res_err) {

  if (res_err == null) {

    console.log("Book updated !");

  } else {

    res_err.printStackTrace();
  }

});</code></pre>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_replacing_documents">Replacing documents</h3>
<div class="paragraph">
<p>To replace documents you use <code><a href="../../jsdoc/module-vertx-mongo-js_mongo_client-MongoClient.html#replace">replace</a></code>.</p>
</div>
<div class="paragraph">
<p>This is similar to the update operation, however it does not take any update operators like <code>update</code>.
Instead it replaces the entire document with the one provided.</p>
</div>
<div class="paragraph">
<p>Here&#8217;s an example of replacing a document in the books collection</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-js" data-lang="js">var query = {
  "title" : "The Hobbit"
};

var replace = {
  "title" : "The Lord of the Rings",
  "author" : "J. R. R. Tolkien"
};

mongoClient.replace("books", query, replace, function (res, res_err) {

  if (res_err == null) {

    console.log("Book replaced !");

  } else {

    res_err.printStackTrace();

  }

});</code></pre>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_finding_documents">Finding documents</h3>
<div class="paragraph">
<p>To find documents you use <code><a href="../../jsdoc/module-vertx-mongo-js_mongo_client-MongoClient.html#find">find</a></code>.</p>
</div>
<div class="paragraph">
<p>The <code>query</code> parameter is used to match the documents in the collection.</p>
</div>
<div class="paragraph">
<p>Here&#8217;s a simple example with an empty query that will match all books:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-js" data-lang="js">// empty query = match any
var query = {
};

mongoClient.find("books", query, function (res, res_err) {

  if (res_err == null) {

    Array.prototype.forEach.call(res, function(json) {

      console.log(JSON.stringify(json));

    });

  } else {

    res_err.printStackTrace();

  }

});</code></pre>
</div>
</div>
<div class="paragraph">
<p>Here&#8217;s another example that will match all books by Tolkien:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-js" data-lang="js">// will match all Tolkien books
var query = {
  "author" : "J. R. R. Tolkien"
};

mongoClient.find("books", query, function (res, res_err) {

  if (res_err == null) {

    Array.prototype.forEach.call(res, function(json) {

      console.log(JSON.stringify(json));

    });

  } else {

    res_err.printStackTrace();

  }

});</code></pre>
</div>
</div>
<div class="paragraph">
<p>The matching documents are returned as a list of json objects in the result handler.</p>
</div>
<div class="paragraph">
<p>To specify things like what fields to return, how many results to return, etc use <code><a href="../../jsdoc/module-vertx-mongo-js_mongo_client-MongoClient.html#findWithOptions">findWithOptions</a></code>
and pass in the an instance of <code><a href="../dataobjects.html#FindOptions">FindOptions</a></code>.</p>
</div>
<div class="paragraph">
<p>This has the following fields:</p>
</div>
<div class="dlist">
<dl>
<dt class="hdlist1"><code>fields</code></dt>
<dd>
<p>The fields to return in the results. Defaults to <code>null</code>, meaning all fields will be returned</p>
</dd>
<dt class="hdlist1"><code>sort</code></dt>
<dd>
<p>The fields to sort by. Defaults to <code>null</code>.</p>
</dd>
<dt class="hdlist1"><code>limit</code></dt>
<dd>
<p>The limit of the number of results to return. Default to <code>-1</code>, meaning all results will be returned.</p>
</dd>
<dt class="hdlist1"><code>skip</code></dt>
<dd>
<p>The number of documents to skip before returning the results. Defaults to <code>0</code>.</p>
</dd>
</dl>
</div>
<div class="listingblock">
<div class="content">
<pre>// will match all Tolkien books
var query = {
  "author" : "J. R. R. Tolkien"
};

mongoClient.findBatch("book", query, function (res, res_err) {

  if (res_err == null) {

    if (res === null) {

      console.log("End of research");

    } else {

      console.log("Found doc: " + JSON.stringify(res));

    }

  } else {

    res_err.printStackTrace();

  }
});</pre>
</div>
</div>
<div class="paragraph">
<p>The matching documents are returned unitary in the result handler.</p>
</div>
</div>
<div class="sect2">
<h3 id="_finding_a_single_document">Finding a single document</h3>
<div class="paragraph">
<p>To find a single document you use <code><a href="../../jsdoc/module-vertx-mongo-js_mongo_client-MongoClient.html#findOne">findOne</a></code>.</p>
</div>
<div class="paragraph">
<p>This works just like <code><a href="../../jsdoc/module-vertx-mongo-js_mongo_client-MongoClient.html#find">find</a></code> but it returns just the first matching document.</p>
</div>
</div>
<div class="sect2">
<h3 id="_removing_documents">Removing documents</h3>
<div class="paragraph">
<p>To remove documents use <code><a href="../../jsdoc/module-vertx-mongo-js_mongo_client-MongoClient.html#removeDocuments">removeDocuments</a></code>.</p>
</div>
<div class="paragraph">
<p>The <code>query</code> parameter is used to match the documents in the collection to determine which ones to remove.</p>
</div>
<div class="paragraph">
<p>Here&#8217;s an example of removing all Tolkien books:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-js" data-lang="js">var query = {
  "author" : "J. R. R. Tolkien"
};

mongoClient.remove("books", query, function (res, res_err) {

  if (res_err == null) {

    console.log("Never much liked Tolkien stuff!");

  } else {

    res_err.printStackTrace();

  }
});</code></pre>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_removing_a_single_document">Removing a single document</h3>
<div class="paragraph">
<p>To remove a single document you use <code><a href="../../jsdoc/module-vertx-mongo-js_mongo_client-MongoClient.html#removeDocument">removeDocument</a></code>.</p>
</div>
<div class="paragraph">
<p>This works just like <code><a href="../../jsdoc/module-vertx-mongo-js_mongo_client-MongoClient.html#removeDocuments">removeDocuments</a></code> but it removes just the first matching document.</p>
</div>
</div>
<div class="sect2">
<h3 id="_counting_documents">Counting documents</h3>
<div class="paragraph">
<p>To count documents use <code><a href="../../jsdoc/module-vertx-mongo-js_mongo_client-MongoClient.html#count">count</a></code>.</p>
</div>
<div class="paragraph">
<p>Here&#8217;s an example that counts the number of Tolkien books. The number is passed to the result handler.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-js" data-lang="js">var query = {
  "author" : "J. R. R. Tolkien"
};

mongoClient.count("books", query, function (res, res_err) {

  if (res_err == null) {

    var num = res;

  } else {

    res_err.printStackTrace();

  }
});</code></pre>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_managing_mongodb_collections">Managing MongoDB collections</h3>
<div class="paragraph">
<p>All MongoDB documents are stored in collections.</p>
</div>
<div class="paragraph">
<p>To get a list of all collections you can use <code><a href="../../jsdoc/module-vertx-mongo-js_mongo_client-MongoClient.html#getCollections">getCollections</a></code></p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-js" data-lang="js">mongoClient.getCollections(function (res, res_err) {

  if (res_err == null) {

    var collections = res;

  } else {

    res_err.printStackTrace();

  }
});</code></pre>
</div>
</div>
<div class="paragraph">
<p>To create a new collection you can use <code><a href="../../jsdoc/module-vertx-mongo-js_mongo_client-MongoClient.html#createCollection">createCollection</a></code></p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-js" data-lang="js">mongoClient.createCollection("mynewcollectionr", function (res, res_err) {

  if (res_err == null) {

    // Created ok!

  } else {

    res_err.printStackTrace();

  }
});</code></pre>
</div>
</div>
<div class="paragraph">
<p>To drop a collection you can use <code><a href="../../jsdoc/module-vertx-mongo-js_mongo_client-MongoClient.html#dropCollection">dropCollection</a></code></p>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<div class="title">Note</div>
</td>
<td class="content">
Dropping a collection will delete all documents within it!
</td>
</tr>
</table>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-js" data-lang="js">mongoClient.dropCollection("mynewcollectionr", function (res, res_err) {

  if (res_err == null) {

    // Dropped ok!

  } else {

    res_err.printStackTrace();

  }
});</code></pre>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_running_other_mongodb_commands">Running other MongoDB commands</h3>
<div class="paragraph">
<p>You can run arbitrary MongoDB commands with <code><a href="../../jsdoc/module-vertx-mongo-js_mongo_client-MongoClient.html#runCommand">runCommand</a></code>.</p>
</div>
<div class="paragraph">
<p>Commands can be used to run more advanced mongoDB features, such as using MapReduce.
For more information see the mongo docs for supported <a href="http://docs.mongodb.org/manual/reference/command">Commands</a>.</p>
</div>
<div class="paragraph">
<p>Here&#8217;s an example of running an aggregate command. Note that the command name must be specified as a parameter
and also be contained in the JSON that represents the command. This is because JSON is not ordered but BSON is
ordered and MongoDB expects the first BSON entry to be the name of the command. In order for us to know which
of the entries in the JSON is the command name it must be specified as a parameter.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-js" data-lang="js">var command = {
  "aggregate" : "collection_name",
  "pipeline" : [
  ]
};

mongoClient.runCommand("aggregate", command, function (res, res_err) {
  if (res_err == null) {
    var resArr = res.result;
    // etc
  } else {
    res_err.printStackTrace();
  }
});</code></pre>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_mongodb_extended_json_support">MongoDB Extended JSON support</h3>
<div class="paragraph">
<p>For now, only date, oid and binary types are supported (cf <a href="http://docs.mongodb.org/manual/reference/mongodb-extended-json" class="bare">http://docs.mongodb.org/manual/reference/mongodb-extended-json</a> )</p>
</div>
<div class="paragraph">
<p>Here&#8217;s an example of inserting a document with a date field</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-js" data-lang="js">var document = {
  "title" : "The Hobbit",
  "publicationDate" : {
    "$date" : "1937-09-21T00:00:00+00:00"
  }
};

mongoService.save("publishedBooks", document, function (res, res_err) {

  if (res_err == null) {

    var id = res;

    mongoService.findOne("publishedBooks", {
      "_id" : id
    }, null, function (res2, res2_err) {
      if (res2_err == null) {

        console.log("To retrieve ISO-8601 date : " + res2.publicationDate.$date);

      } else {
        res2_err.printStackTrace();
      }
    });

  } else {
    res_err.printStackTrace();
  }

});</code></pre>
</div>
</div>
<div class="paragraph">
<p>Here&#8217;s an example (in Java) of inserting a document with a binary field and reading it back</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-js" data-lang="js">byte[] binaryObject = new byte[40];

JsonObject document = new JsonObject()
        .put("name", "Alan Turing")
        .put("binaryStuff", new JsonObject().put("$binary", binaryObject));

mongoService.save("smartPeople", document, res -&gt; {

  if (res.succeeded()) {

    String id = res.result();

    mongoService.findOne("smartPeople", new JsonObject().put("_id", id), null, res2 -&gt; {
      if(res2.succeeded()) {

        byte[] reconstitutedBinaryObject = res2.result().getJsonObject("binaryStuff").getBinary("$binary");
        //This could now be de-serialized into an object in real life
      } else {
        res2.cause().printStackTrace();
      }
    });

  } else {
    res.cause().printStackTrace();
  }

});</code></pre>
</div>
</div>
<div class="paragraph">
<p>Here&#8217;s an example of inserting a base 64 encoded string, typing it as binary a binary field, and reading it back</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-js" data-lang="js">//This could be a the byte contents of a pdf file, etc converted to base 64
var base64EncodedString = "a2FpbHVhIGlzIHRoZSAjMSBiZWFjaCBpbiB0aGUgd29ybGQ=";

var document = {
  "name" : "Alan Turing",
  "binaryStuff" : {
    "$binary" : base64EncodedString
  }
};

mongoService.save("smartPeople", document, function (res, res_err) {

  if (res_err == null) {

    var id = res;

    mongoService.findOne("smartPeople", {
      "_id" : id
    }, null, function (res2, res2_err) {
      if (res2_err == null) {

        var reconstitutedBase64EncodedString = res2.binaryStuff.$binary;
        //This could now converted back to bytes from the base 64 string
      } else {
        res2_err.printStackTrace();
      }
    });

  } else {
    res_err.printStackTrace();
  }

});</code></pre>
</div>
</div>
<div class="paragraph">
<p>Here&#8217;s an example of inserting an object ID and reading it back</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-js" data-lang="js">var individualId = new (Java.type("org.bson.types.ObjectId"))().toHexString();

var document = {
  "name" : "Stephen Hawking",
  "individualId" : {
    "$oid" : individualId
  }
};

mongoService.save("smartPeople", document, function (res, res_err) {

  if (res_err == null) {

    var id = res;

    mongoService.findOne("smartPeople", {
      "_id" : id
    }, null, function (res2, res2_err) {
      if (res2_err == null) {
        var reconstitutedIndividualId = res2.individualId.$oid;
      } else {
        res2_err.printStackTrace();
      }
    });

  } else {
    res_err.printStackTrace();
  }

});</code></pre>
</div>
</div>
<div class="paragraph">
<p>Here&#8217;s an example of getting disting value</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-js" data-lang="js">Code not translatable</code></pre>
</div>
</div>
<div class="paragraph">
<p>Here&#8217;s an example of getting distinct value in batch mode</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-js" data-lang="js">Code not translatable</code></pre>
</div>
</div>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_configuring_the_client">Configuring the client</h2>
<div class="sectionbody">
<div class="paragraph">
<p>The client is configured with a json object.</p>
</div>
<div class="paragraph">
<p>The following configuration is supported by the mongo client:</p>
</div>
<div class="dlist">
<dl>
<dt class="hdlist1"><code>db_name</code></dt>
<dd>
<p>Name of the database in the mongoDB instance to use. Defaults to <code>default_db</code></p>
</dd>
<dt class="hdlist1"><code>useObjectId</code></dt>
<dd>
<p>Toggle this option to support persisting and retrieving ObjectId&#8217;s as strings. If <code>true', hex-strings will
be saved as native Mongodb ObjectId types in the document collection. This will allow the sorting of documents based on creation
time. You can also derive the creation time from the hex-string using ObjectId::getDate(). Set to `false' for other types of your choosing.
If set to false, or left to default, hex strings will be generated as the document _id if the _id is omitted from the document.
Defaults to `false</code>.</p>
</dd>
</dl>
</div>
<div class="paragraph">
<p>The mongo client tries to support most options that are allowed by the driver. There are two ways to configure mongo
for use by the driver, either by a connection string or by separate configuration options.</p>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<div class="title">Note</div>
</td>
<td class="content">
If the connection string is used the mongo client will ignore any driver configuration options.
</td>
</tr>
</table>
</div>
<div class="dlist">
<dl>
<dt class="hdlist1"><code>connection_string</code></dt>
<dd>
<p>The connection string the driver uses to create the client. E.g. <code>mongodb://localhost:27017</code>.
For more information on the format of the connection string please consult the driver documentation.</p>
</dd>
</dl>
</div>
<div class="paragraph">
<p><strong>Specific driver configuration options</strong></p>
</div>
<div class="listingblock">
<div class="content">
<pre>{
  // Single Cluster Settings
  "host" : "17.0.0.1", // string
  "port" : 27017,      // int

  // Multiple Cluster Settings
  "hosts" : [
    {
      "host" : "cluster1", // string
      "port" : 27000       // int
    },
    {
      "host" : "cluster2", // string
      "port" : 28000       // int
    },
    ...
  ],
  "replicaSet" :  "foo"    // string

  // Connection Pool Settings
  "maxPoolSize" : 50,                // int
  "minPoolSize" : 25,                // int
  "maxIdleTimeMS" : 300000,          // long
  "maxLifeTimeMS" : 3600000,         // long
  "waitQueueMultiple"  : 10,         // int
  "waitQueueTimeoutMS" : 10000,      // long
  "maintenanceFrequencyMS" : 2000,   // long
  "maintenanceInitialDelayMS" : 500, // long

  // Credentials / Auth
  "username"   : "john",     // string
  "password"   : "passw0rd", // string
  "authSource" : "some.db"   // string
  // Auth mechanism
  "authMechanism"     : "GSSAPI",        // string
  "gssapiServiceName" : "myservicename", // string

  // Socket Settings
  "connectTimeoutMS" : 300000, // int
  "socketTimeoutMS"  : 100000, // int
  "sendBufferSize"    : 8192,  // int
  "receiveBufferSize" : 8192,  // int
  "keepAlive" : true           // boolean

  // Heartbeat socket settings
  "heartbeat.socket" : {
  "connectTimeoutMS" : 300000, // int
  "socketTimeoutMS"  : 100000, // int
  "sendBufferSize"    : 8192,  // int
  "receiveBufferSize" : 8192,  // int
  "keepAlive" : true           // boolean
  }

  // Server Settings
  "heartbeatFrequencyMS" :    1000 // long
  "minHeartbeatFrequencyMS" : 500 // long
}</pre>
</div>
</div>
<div class="paragraph">
<p><strong>Driver option descriptions</strong></p>
</div>
<div class="dlist">
<dl>
<dt class="hdlist1"><code>host</code></dt>
<dd>
<p>The host the mongoDB instance is running. Defaults to <code>127.0.0.1</code>. This is ignored if <code>hosts</code> is specified</p>
</dd>
<dt class="hdlist1"><code>port</code></dt>
<dd>
<p>The port the mongoDB instance is listening on. Defaults to <code>27017</code>. This is ignored if <code>hosts</code> is specified</p>
</dd>
<dt class="hdlist1"><code>hosts</code></dt>
<dd>
<p>An array representing the hosts and ports to support a mongoDB cluster (sharding / replication)</p>
</dd>
<dt class="hdlist1"><code>host</code></dt>
<dd>
<p>A host in the cluster</p>
</dd>
<dt class="hdlist1"><code>port</code></dt>
<dd>
<p>The port a host in the cluster is listening on</p>
</dd>
<dt class="hdlist1"><code>replicaSet</code></dt>
<dd>
<p>The name of the replica set, if the mongoDB instance is a member of a replica set</p>
</dd>
<dt class="hdlist1"><code>maxPoolSize</code></dt>
<dd>
<p>The maximum number of connections in the connection pool. The default value is <code>100</code></p>
</dd>
<dt class="hdlist1"><code>minPoolSize</code></dt>
<dd>
<p>The minimum number of connections in the connection pool. The default value is <code>0</code></p>
</dd>
<dt class="hdlist1"><code>maxIdleTimeMS</code></dt>
<dd>
<p>The maximum idle time of a pooled connection. The default value is <code>0</code> which means there is no limit</p>
</dd>
<dt class="hdlist1"><code>maxLifeTimeMS</code></dt>
<dd>
<p>The maximum time a pooled connection can live for. The default value is <code>0</code> which means there is no limit</p>
</dd>
<dt class="hdlist1"><code>waitQueueMultiple</code></dt>
<dd>
<p>The maximum number of waiters for a connection to become available from the pool. Default value is <code>500</code></p>
</dd>
<dt class="hdlist1"><code>waitQueueTimeoutMS</code></dt>
<dd>
<p>The maximum time that a thread may wait for a connection to become available. Default value is <code>120000</code> (2 minutes)</p>
</dd>
<dt class="hdlist1"><code>maintenanceFrequencyMS</code></dt>
<dd>
<p>The time period between runs of the maintenance job. Default is <code>0</code>.</p>
</dd>
<dt class="hdlist1"><code>maintenanceInitialDelayMS</code></dt>
<dd>
<p>The period of time to wait before running the first maintenance job on the connection pool. Default is <code>0</code>.</p>
</dd>
<dt class="hdlist1"><code>username</code></dt>
<dd>
<p>The username to authenticate. Default is <code>null</code> (meaning no authentication required)</p>
</dd>
<dt class="hdlist1"><code>password</code></dt>
<dd>
<p>The password to use to authenticate.</p>
</dd>
<dt class="hdlist1"><code>authSource</code></dt>
<dd>
<p>The database name associated with the user&#8217;s credentials. Default value is the <code>db_name</code> value.</p>
</dd>
<dt class="hdlist1"><code>authMechanism</code></dt>
<dd>
<p>The authentication mechanism to use. See [Authentication](<a href="http://docs.mongodb.org/manual/core/authentication/" class="bare">http://docs.mongodb.org/manual/core/authentication/</a>) for more details.</p>
</dd>
<dt class="hdlist1"><code>gssapiServiceName</code></dt>
<dd>
<p>The Kerberos service name if <code>GSSAPI</code> is specified as the <code>authMechanism</code>.</p>
</dd>
<dt class="hdlist1"><code>connectTimeoutMS</code></dt>
<dd>
<p>The time in milliseconds to attempt a connection before timing out. Default is <code>10000</code> (10 seconds)</p>
</dd>
<dt class="hdlist1"><code>socketTimeoutMS</code></dt>
<dd>
<p>The time in milliseconds to attempt a send or receive on a socket before the attempt times out. Default is <code>0</code> meaning there is no timeout</p>
</dd>
<dt class="hdlist1"><code>sendBufferSize</code></dt>
<dd>
<p>Sets the send buffer size (SO_SNDBUF) for the socket. Default is <code>0</code>, meaning it will use the OS default for this option.</p>
</dd>
<dt class="hdlist1"><code>receiveBufferSize</code></dt>
<dd>
<p>Sets the receive buffer size (SO_RCVBUF) for the socket. Default is <code>0</code>, meaning it will use the OS default for this option.</p>
</dd>
<dt class="hdlist1"><code>keepAlive</code></dt>
<dd>
<p>Sets the keep alive (SO_KEEPALIVE) for the socket. Default is <code>false</code></p>
</dd>
<dt class="hdlist1"><code>heartbeat.socket</code></dt>
<dd>
<p>Configures the socket settings for the cluster monitor of the MongoDB java driver.</p>
</dd>
<dt class="hdlist1"><code>heartbeatFrequencyMS</code></dt>
<dd>
<p>The frequency that the cluster monitor attempts to reach each server. Default is <code>5000</code> (5 seconds)</p>
</dd>
<dt class="hdlist1"><code>minHeartbeatFrequencyMS</code></dt>
<dd>
<p>The minimum heartbeat frequency. The default value is <code>1000</code> (1 second)</p>
</dd>
</dl>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<div class="title">Note</div>
</td>
<td class="content">
Most of the default values listed above use the default values of the MongoDB Java Driver.
Please consult the driver documentation for up to date information.
</td>
</tr>
</table>
</div>
</div>
</div>

        

        
          <div id="footer">
            <div id="footer-text">
              
                Last updated 2016-09-12 08:38:04 CEST
              
              
            </div>
          </div>
        
      </div>
    </div>
  </div>
</div>

<footer>
  <div class="container">
    <div class="row">
      <div class="col-xs-6 col-sm-3 col-md-3 col-lg-2">
        <h2>Vert.x</h2>
        <ul class="list-unstyled">
          <li><a href="http://vertx.io/">Home</a></li>
          <li><a href="http://vertx.io/download/">Download</a></li>
          <li><a href="http://vertx.io/docs/">Documentation</a></li>
          <li><a href="https://github.com/vert-x3/wiki/wiki">Wiki</a></li>
          <li><a href="http://vertx.io/blog/">Blog</a></li>
          <li><a href="http://vertx.io/vertx2/" class="vertx-2-link">Vert.x 2</a></li>
        </ul>
      </div>
      <div class="col-xs-6 col-sm-3 col-md-3 col-lg-2">
        <h2>Community</h2>
        <ul class="list-unstyled">
          <li><a href="http://vertx.io/community/">Help &amp; Contributors</a></li>
          <li><a href="http://vertx.io/materials/">Learning materials</a></li>
          <li><a href="https://groups.google.com/forum/?fromgroups#!forum/vertx">User Group</a></li>
          <li><a href="https://groups.google.com/forum/?fromgroups#!forum/vertx-dev">Developer Group</a></li>
        </ul>
      </div>

      <div class="col-xs-12 col-sm-6 col-lg-offset-2 col-md-6 copyright">
        <p>Vert.x is open source and dual licensed under the <a href="https://www.eclipse.org/org/documents/epl-v10.php">Eclipse Public License 1.0</a> and <a href="https://www.apache.org/licenses/LICENSE-2.0.html">Apache License 2.0</a>.</p>
        <p>This website is licensed under the <a href="http://creativecommons.org/licenses/by-sa/3.0/">CC BY-SA 3.0 License</a>.<br>
        Design by <a href="http://www.michel-kraemer.com">Michel Kr&auml;mer</a>. <a href="http://www.entypo.com">Entypo pictograms</a> by Daniel Bruce.</p>
        <div class="row">
          <div class="col-xs-12 col-lg-offset-1 col-md-5">
            <a href="http://eclipse.org">
            <img class="logo eclipse-logo" src="http://vertx.io/assets/eclipse_logo_grey_small.png" width="204" height="48">
            </a>
          </div>
          <div class="col-xs-12 col-md-offset-2 col-lg-offset-0 col-md-5">
            <a href="http://cloudbees.com">
            <img class="logo cloudbees-logo" src="http://vertx.io/assets/Button-Built-on-CB-1-grey.png" width="180" height="48">
           </a>
          </div>
          <div class="col-xs-12 col-md-offset-2 col-lg-offset-1 col-md-5 jprofiler">
            <a href="http://www.ej-technologies.com/products/jprofiler/overview.html"
            style="text-decoration:none">
            <img class="logo jprofiler-logo" src="http://vertx.io/assets/jprofiler-logo.png" width="48" height="48"><span class="jprofiler-logo">&nbsp; JPROFILER</span>
            </a>
          </div>
        </div>
      </div>
    </div>
  </div>
</footer>

<script src="http://static.jboss.org/theme/js/libs/jquery/jquery-1.9.1.min.js"></script>
<script src="http://vertx.io/javascripts/bootstrap.min.js"></script>
<script src="http://vertx.io/javascripts/highlight.pack.js"></script>
<script>hljs.initHighlightingOnLoad();</script>



<script src="http://vertx.io/javascripts/sidebar.js"></script>


</body>
</html>
